<template>
  <view class="chat-container">
    <view v-if="reconnecting" style="background:#fffbe6;color:#8c6d1f;padding:12rpx 20rpx;font-size:22rpx;border-bottom:1rpx solid #f0e6cc;display:flex;align-items:center;gap:12rpx;">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="header-left">
        <button class="back-btn" @click="goBack">←</button>
        <view class="user-info">
          <text class="user-name">{{ currentChatUser.name || '聊天' }}</text>
          <text class="user-status">{{ currentChatUser.isOnline ? '在线' : '离线' }}</text>
        </view>
      </view>
      <view class="header-right">
        <text class="conn-status" :class="['status-icon', getConnectionStatusClass()]">{{ getConnectionStatusIcon() }}</text>
        <button class="call-btn" @click="makeCall">📞</button>
        <button class="more-btn" @click="showMoreOptions">⋯</button>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view 
      ref="scrollView"
      class="message-list" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      :scroll-into-view="scrollIntoView"
      @scrolltoupper="loadMoreMessages"
    >
      <view 
        v-for="(message, index) in visibleMessages" 
        :key="message.id || index"
        :id="`message-${message.id || index}`"
        class="message-item"
        :class="getMessageClass(message)"
      >
        <view class="message-avatar">
          <image 
            v-if="message.sender?.avatar" 
            :src="message.sender.avatar" 
            class="avatar-image"
            mode="aspectFill"
          />
          <text v-else class="avatar-text">{{ getAvatarText(message) }}</text>
        </view>
        <view class="message-content">
          <view class="message-header">
            <text class="sender-name">{{ message.sender?.name || '系统' }}</text>
            <text class="message-time">{{ formatTime(message.timestamp) }}</text>
          </view>
          <view class="message-body">
            <text v-if="message.type === 'text'" class="message-text">{{ message.content }}</text>
            <image v-else-if="message.type === 'image'" 
              :src="message.content" 
              class="message-image"
              mode="aspectFit"
              @click="previewImage(message.content)"
            />
            <view v-else-if="message.type === 'file'" class="message-file">
              <text class="file-icon">📎</text>
              <text class="file-name">{{ message.fileName }}</text>
            </view>
          </view>
          <view class="message-status" v-if="message.status && isMyMessage(message)">
            <text class="status-icon">{{ getMessageStatusIcon(message.status) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view v-if="loadingMore" class="loading-more">
        <text class="loading-text">加载更多消息...</text>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <view class="input-toolbar">
        <button class="tool-btn" @click="showEmojiPicker">😊</button>
        <button class="tool-btn" @click="chooseImage">📷</button>
        <button class="tool-btn" @click="chooseFile">📎</button>
        <button class="tool-btn" @click="showVoiceRecord">🎤</button>
      </view>
      <view class="input-row">
        <input 
          class="message-input" 
          v-model="inputMessage" 
          placeholder="输入消息..."
          @confirm="sendMessage"
          @focus="scrollToBottom"
        />
        <button 
          class="send-btn" 
          @click="sendMessage"
          :disabled="!inputMessage.trim()"
        >
          发送
        </button>
      </view>
    </view>

    <!-- 表情选择器 -->
    <SheetModal 
      :visible="showEmojiModal" 
      title="选择表情" 
      :show-close="true"
      @close="closeEmojiModal"
    >
      <view class="emoji-grid">
        <view 
          v-for="emoji in emojis" 
          :key="emoji"
          class="emoji-item"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </view>
      </view>
    </SheetModal>

    <!-- 更多选项弹窗 -->
    <SheetModal 
      :visible="showMoreOptionsModal" 
      title="更多选项" 
      :show-close="true"
      @close="closeMoreOptions"
    >
      <view class="options-list">
        <view class="option-item" @click="clearMessages">
          <text class="option-icon">🗑️</text>
          <text class="option-text">清空消息</text>
        </view>
        <view class="option-item" @click="exportMessages">
          <text class="option-icon">📤</text>
          <text class="option-text">导出聊天记录</text>
        </view>
        <view class="option-item" @click="showChatSettings">
          <text class="option-icon">⚙️</text>
          <text class="option-text">聊天设置</text>
        </view>
      </view>
    </SheetModal>
  </view>
</template>

<script>
import chatService from '../../utils/websocket-chat-service.js'
import apiService from '../../utils/api-service.js'
import appStateManager from '../../utils/app-state-manager.js'
import connectionManager from '../../utils/connection-manager.js'
import chatMessageManager from '../../utils/chat-message-manager.js'
import notificationService from '../../utils/notification-service.js'
import SheetModal from '../../components/SheetModal.vue'

export default {
  components: {
    SheetModal
  },
  
  data() {
    return {
      // 聊天相关
      messages: [],
      inputMessage: '',
      currentChatUser: {
        id: '',
        name: '聊天用户',
        avatar: '',
        isOnline: true
      },
      roomId: '',
      scrollTop: 0,
      scrollIntoView: '',
      loadingMore: false,
      isSending: false,
      isInitialLoad: true,
      scrollLock: false,
      maxVisibleMessages: 50,
      
      // 简化的状态管理 - 通过订阅获取
      serverOnline: false,
      chatConnected: false,
      reconnecting: false,
      
      // 弹窗状态
      showEmojiModal: false,
      showMoreOptionsModal: false,
      
      // 表情数据
      emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓']
    }
  },
  
  computed: {
    // 虚拟滚动 - 只显示最近的消息
    visibleMessages() {
      if (this.messages.length <= this.maxVisibleMessages) {
        return this.messages
      }
      return this.messages.slice(-this.maxVisibleMessages)
    }
  },
  
  async onLoad(options) {
    console.log('聊天页面加载，参数:', options)
    
    try {
      // 检查必要参数
      if (!options || !options.userId) {
        throw new Error('缺少必要的用户ID参数')
      }
      
      // 获取聊天用户信息
      if (options.userName) {
        console.log('使用URL中的用户名:', options.userName)
        this.currentChatUser = {
          id: options.userId,
          name: options.userName,
          avatar: '',
          isOnline: false
        }
        console.log('设置用户信息为:', this.currentChatUser)
      } else {
        await this.loadChatUser(options.userId)
      }
      
      // 生成房间ID
      this.roomId = this.generateRoomId()
      console.log('生成房间ID:', this.roomId)
      
      // 初始化状态订阅
      this.initStateSubscriptions()
      
      // 订阅消息管理器
      this.subscribeToMessages()
      
      // 初始化聊天服务
      await this.initChatService()
      
      // 只有在聊天服务初始化成功后才加入房间和拉取历史消息
      if (chatService.isConnected) {
        // 延迟加入房间和拉取历史消息
        setTimeout(async () => {
          try {
            console.log('准备加入房间:', this.roomId)
            await chatService.joinRoom(this.roomId)
            console.log('成功加入房间:', this.roomId)
            await this.loadHistoryMessages()
            console.log('历史消息加载完成')
          } catch (e) {
            console.error('加入房间失败:', e)
            uni.showToast({
              title: '加入聊天室失败',
              icon: 'none'
            })
          }
        }, 1000) // 缩短延迟时间
      } else {
        console.log('聊天服务未连接，跳过加入房间')
      }
    } catch (error) {
      console.error('聊天页面加载失败:', error)
      uni.showModal({
        title: '加载失败',
        content: error.message || '聊天页面加载失败',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
    }
  },
  
  async onShow() {
    // 页面显示时刷新状态
    setTimeout(() => {
      appStateManager.refreshServerStatus()
      
      // 刷新在线状态
      if (chatService.isConnected) {
        chatService.requestOnlineUsers()
      }
    }, 500)
    
    // 标记与当前聊天用户相关的通知为已读
    this.markUserNotificationsAsRead()
  },
  
  async onUnload() {
    try { 
      await chatService.leaveRoom(this.roomId) 
    } catch (e) {
      console.error('离开房间失败:', e)
    }
    this.cleanup()
  },
  
  methods: {
    // ==================== 新的状态管理方法 ====================
    
    // 初始化状态订阅
    initStateSubscriptions() {
      console.log('初始化状态订阅...')
      
      // 订阅服务器状态
      appStateManager.subscribe('server', (serverState) => {
        this.serverOnline = serverState.isOnline
        console.log('服务器状态更新:', serverState.isOnline ? '在线' : '离线')
      })
      
      // 订阅聊天连接状态
      appStateManager.subscribe('chat', (chatState) => {
        this.chatConnected = chatState.isConnected
        this.reconnecting = chatState.reconnectAttempts > 0
        console.log('聊天连接状态更新:', chatState.isConnected ? '已连接' : '未连接')
      })
      
      // 注册WebSocket服务到连接管理器
      connectionManager.setWebSocketService(chatService)
      connectionManager.start()
    },
    
    // 订阅消息管理器
    subscribeToMessages() {
      console.log('订阅消息管理器...')
      chatMessageManager.subscribe(this.roomId, (messages) => {
        this.messages = messages
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })
    },
    
    // 生成房间ID
    generateRoomId() {
      const currentUser = this.getCurrentUser()
      if (!currentUser || !this.currentChatUser.id) {
        return `room_${Date.now()}`
      }
      
      return chatMessageManager.generateRoomId([
        currentUser.id.toString(),
        this.currentChatUser.id.toString()
      ], 'private')
    },
    
    // 加载历史消息
    async loadHistoryMessages() {
      try {
        console.log('开始加载历史消息，房间ID:', this.roomId)
        const res = await apiService.get(`/chat/messages?room_id=${encodeURIComponent(this.roomId)}`)
        
        if (res && res.code === 'SUCCESS' && Array.isArray(res.data)) {
          console.log('获取到历史消息:', res.data.length, '条')
          chatMessageManager.setHistoryMessages(this.roomId, res.data)
        }
      } catch (error) {
        console.error('加载历史消息失败:', error)
      }
    },
    
    // ==================== 原有方法 ====================
    
    // 加载聊天用户信息
    async loadChatUser(userId) {
      try {
        console.log('开始加载聊天用户信息，用户ID:', userId)
        
        // 从本地存储的好友列表中查找用户信息
        const friendsList = uni.getStorageSync('friends_list') || []
        console.log('本地好友列表:', friendsList)
        
        const friend = friendsList.find(f => f.id == userId)
        console.log('找到的好友信息:', friend)
        
        if (friend) {
          this.currentChatUser = {
            id: friend.id,
            name: friend.name,
            avatar: friend.avatar || '',
            isOnline: friend.isOnline || false
          }
          console.log('使用本地好友信息:', this.currentChatUser)
        } else {
          console.log('本地未找到好友信息，尝试从服务器获取')
          // 如果本地没有找到，尝试从服务器获取
          const response = await apiService.get(`/friends/${userId}`)
          console.log('服务器返回的好友信息:', response)
          
          if (response && response.data) {
            this.currentChatUser = {
              id: response.data.id,
              name: response.data.name,
              avatar: response.data.avatar || '',
              isOnline: response.data.isOnline || false
            }
            console.log('使用服务器好友信息:', this.currentChatUser)
          } else {
            // 如果都找不到，使用默认信息
            this.currentChatUser = {
              id: userId,
              name: '用户' + userId,
              avatar: '',
              isOnline: false
            }
            console.log('使用默认用户信息:', this.currentChatUser)
          }
        }
      } catch (error) {
        console.error('加载聊天用户信息失败:', error)
        // 使用默认信息
        this.currentChatUser = {
          id: userId,
          name: '用户' + userId,
          avatar: '',
          isOnline: false
        }
        console.log('异常情况下使用默认用户信息:', this.currentChatUser)
      }
    },
    
    // 初始化聊天服务（增强版）
    async initChatService() {
      try {
        console.log('开始初始化聊天服务...')
        
        // 检查网络状态
        const networkInfo = await this.checkNetworkStatus()
        if (!networkInfo.isConnected) {
          throw new Error('网络连接不可用，请检查网络设置')
        }
        
        // 检查服务器状态
        const serverStatus = appStateManager.getState('server')
        if (!serverStatus.isOnline) {
          // 尝试刷新服务器状态
          console.log('服务器状态离线，尝试刷新状态...')
          const isOnline = await appStateManager.refreshServerStatus()
          if (!isOnline) {
            throw new Error('服务器连接失败，请稍后再试')
          }
        }
        
        // 初始化WebSocket连接
        await chatService.init()
        console.log('聊天服务初始化完成')
        
        // 监听消息并转发给消息管理器
        chatService.onMessage((message) => {
          console.log('收到WebSocket消息:', message)
          chatMessageManager.handleServerMessage(message)
        })
        
        // 监听状态变化并更新应用状态
        chatService.onStatusChange((statusInfo) => {
          console.log('聊天服务状态变化:', statusInfo)
          
          // 更新聊天连接状态
          const isConnected = statusInfo.status === 'connected' || statusInfo.status === 'online_users'
          const reconnectAttempts = statusInfo.status === 'reconnecting' ? 1 : 0
          
          appStateManager.updateChatConnectionStatus(isConnected, reconnectAttempts)
          
          // 显示重连状态
          this.reconnecting = statusInfo.status === 'reconnecting'
          
          // 连接成功后请求在线用户列表
          if (statusInfo.status === 'connected') {
            chatService.requestOnlineUsers()
          }
        })
        
        // 监听在线状态变化
        chatService.onOnlineStatusChange((statusInfo) => {
          console.log('[Chat] 收到在线状态变化:', statusInfo)
          const isCurrentUserOnline = statusInfo.online.includes(parseInt(this.currentChatUser.id))
          console.log('[Chat] 当前聊天用户在线状态:', isCurrentUserOnline)
          this.currentChatUser.isOnline = isCurrentUserOnline
        })
        
        // 如果已连接，立即获取在线状态
        if (chatService.isConnected) {
          const onlineUsers = chatService.getOnlineUsers()
          const isCurrentUserOnline = onlineUsers.includes(parseInt(this.currentChatUser.id))
          this.currentChatUser.isOnline = isCurrentUserOnline
          console.log('[Chat] 初始化时设置在线状态:', isCurrentUserOnline)
        }
        
      } catch (error) {
        console.error('初始化聊天服务失败:', error)
        
        // 显示详细错误信息
        let errorMessage = '聊天服务初始化失败'
        if (error.message) {
          errorMessage += `: ${error.message}`
        }
        
        // 显示错误提示
        uni.showModal({
          title: '连接失败',
          content: errorMessage,
          confirmText: '重试',
          cancelText: '返回',
          success: (res) => {
            if (res.confirm) {
              // 用户点击重试
              console.log('用户选择重试连接')
              setTimeout(() => {
                this.initChatService()
              }, 1000)
            } else {
              // 用户点击返回
              uni.navigateBack()
            }
          }
        })
      }
    },
    
    // 检查网络状态
    async checkNetworkStatus() {
      return new Promise((resolve) => {
        // #ifdef H5
        // 网页端检查网络连接
        const isOnline = navigator.onLine
        resolve({
          networkType: 'wifi',
          isConnected: isOnline
        })
        // #endif
        
        // #ifdef APP-PLUS || MP
        // App端和小程序端使用uni.getNetworkType
        uni.getNetworkType({
          success: (res) => {
            resolve({
              networkType: res.networkType,
              isConnected: res.networkType !== 'none'
            })
          },
          fail: () => {
            resolve({
              networkType: 'unknown',
              isConnected: false
            })
          }
        })
        // #endif
      })
    },
    

    

    
    // 更新用户在线状态
    async updateUserOnlineStatus() {
      try {
        console.log('更新用户在线状态...')
        
        // 从本地好友列表获取最新状态
        const friendsListData = uni.getStorageSync('friends_list')
        console.log('本地好友列表数据:', friendsListData)
        
        let friendsList = []
        if (Array.isArray(friendsListData)) {
          friendsList = friendsListData
        } else if (friendsListData && typeof friendsListData === 'string') {
          try {
            friendsList = JSON.parse(friendsListData)
          } catch (e) {
            console.error('解析好友列表数据失败:', e)
            friendsList = []
          }
        }
        
        console.log('处理后的好友列表:', friendsList)
        const friend = friendsList.find(f => f.id == this.currentChatUser.id)
        
        if (friend) {
          console.log('找到好友信息，更新在线状态:', friend.isOnline)
          this.currentChatUser.isOnline = friend.isOnline || false
        } else {
          console.log('本地未找到好友信息，尝试从服务器获取')
          // 如果本地没有，尝试从服务器获取
          try {
            const response = await apiService.get(`/friends/${this.currentChatUser.id}`)
            if (response && response.data) {
              this.currentChatUser.isOnline = response.data.isOnline || false
              console.log('从服务器获取在线状态:', this.currentChatUser.isOnline)
            }
          } catch (error) {
            console.error('从服务器获取用户状态失败:', error)
          }
        }
        
        console.log('用户在线状态已更新:', this.currentChatUser.isOnline)
      } catch (error) {
        console.error('更新用户在线状态失败:', error)
      }
    },
    
    // 获取连接状态文本（简化版）
    getConnectionStatusText() {
      if (!this.serverOnline) {
        return '服务器离线'
      }
      
      if (this.reconnecting) {
        return '重连中...'
      }
      
      if (this.chatConnected) {
        return '已连接'
      }
      
      return '连接中...'
    },
    // 获取连接状态图标（简洁版）
    getConnectionStatusIcon() {
      if (!this.serverOnline) {
        return '🔴' // 服务器离线
      }

      if (this.reconnecting) {
        return '🟡' // 正在重连
      }

      if (this.chatConnected) {
        return '🟢' // 已连接
      }

      return '🔵' // 初始连接中
    },
    
    // 获取连接状态样式类（简化版）
    getConnectionStatusClass() {
      if (!this.serverOnline) {
        return 'offline'
      }
      
      if (this.reconnecting) {
        return 'reconnecting'
      }
      
      if (this.chatConnected) {
        return 'connected'
      }
      
      return 'connecting'
    },
    

    
    // 发送消息（简化版）
    async sendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }
      
      // 防止重复发送
      if (this.isSending) {
        console.log('正在发送消息，跳过重复发送')
        return
      }
      
      this.isSending = true
      const messageContent = this.inputMessage.trim()
      this.inputMessage = '' // 立即清空输入框
      
      try {
        console.log('发送消息:', messageContent)
        
        // 使用消息管理器发送消息
        await chatMessageManager.sendMessage(
          this.roomId, 
          messageContent, 
          'text', 
          chatService
        )
        
        console.log('消息发送成功')
        
      } catch (error) {
        console.error('发送消息失败:', error)
        uni.showToast({
          title: '发送失败',
          icon: 'error'
        })
        
        // 恢复输入内容
        this.inputMessage = messageContent
      } finally {
        // 重置发送状态
        this.isSending = false
      }
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.sendImageMessage(tempFilePath)
        }
      })
    },
    
    // 发送图片消息
    async sendImageMessage(imagePath) {
      try {
        const currentUser = this.getCurrentUser()
        if (!currentUser) {
          uni.showToast({ title: '用户未登录', icon: 'error' })
          return
        }
        
        const message = {
          content: imagePath,
          type: 'image',
          timestamp: new Date().toISOString(),
          sender: currentUser,
          status: 'sending'
        }
        
        this.messages.push({ ...message, id: Date.now() })
        this.saveMessages()
        
        // 立即滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
        
        // 这里应该上传图片到服务器
        // 暂时使用本地路径
        message.status = 'sent'
        this.saveMessages()
        
      } catch (error) {
        console.error('发送图片失败:', error)
        uni.showToast({
          title: '发送图片失败',
          icon: 'error'
        })
      }
    },
    
    // 选择文件
    chooseFile() {
      uni.showModal({
        title: '选择文件',
        content: '文件选择功能开发中',
        showCancel: false
      })
    },
    
    // 显示语音录制
    showVoiceRecord() {
      uni.showModal({
        title: '语音消息',
        content: '语音录制功能开发中',
        showCancel: false
      })
    },
    
    // 预览图片
    previewImage(imagePath) {
      uni.previewImage({
        urls: [imagePath],
        current: imagePath
      })
    },
    
    // 插入表情
    insertEmoji(emoji) {
      this.inputMessage += emoji
      this.closeEmojiModal()
    },
    
    // 清空消息（使用消息管理器）
    clearMessages() {
      uni.showModal({
        title: '清空消息',
        content: '确定要清空所有消息吗？',
        success: (res) => {
          if (res.confirm) {
            chatMessageManager.clearRoomMessages(this.roomId)
            uni.showToast({
              title: '消息已清空',
              icon: 'success'
            })
          }
        }
      })
      this.closeMoreOptions()
    },
    
    // 导出聊天记录
    exportMessages() {
      try {
        const chatData = {
          user: this.currentChatUser,
          messages: this.messages,
          exportTime: new Date().toISOString()
        }
        
        const dataStr = JSON.stringify(chatData, null, 2)
        uni.setClipboardData({
          data: dataStr,
          success: () => {
            uni.showToast({
              title: '聊天记录已复制到剪贴板',
              icon: 'success'
            })
          }
        })
      } catch (error) {
        console.error('导出失败:', error)
        uni.showToast({
          title: '导出失败',
          icon: 'error'
        })
      }
      this.closeMoreOptions()
    },
    
    // 显示聊天设置
    showChatSettings() {
      uni.showToast({
        title: '聊天设置功能开发中',
        icon: 'none'
      })
      this.closeMoreOptions()
    },
    
    // 拨打电话
    makeCall() {
      uni.showModal({
        title: '语音通话',
        content: '语音通话功能开发中',
        showCancel: false
      })
    },
    
    // 加载更多消息
    loadMoreMessages() {
      if (this.loadingMore) return
      
      this.loadingMore = true
      // 模拟加载更多消息
      setTimeout(() => {
        this.loadingMore = false
      }, 1000)
    },
    
    // 滚动到底部 - 性能优化版本
    scrollToBottom() {
      try {
        if (this.messages.length === 0) {
          return
        }
        
        // 使用nextTick确保DOM更新完成
        this.$nextTick(() => {
          // 简化滚动逻辑，减少延迟
          const lastMessageId = this.messages[this.messages.length - 1].id || (this.messages.length - 1)
          this.scrollIntoView = `message-${lastMessageId}`
          
          // 快速清除scroll-into-view
          setTimeout(() => {
            this.scrollIntoView = ''
          }, 100)
        })
      } catch (error) {
        // 静默处理错误
      }
    },
    
    // 强制滚动到底部（备用方法）
    forceScrollToBottom() {
      try {
        console.log('使用强制滚动方法')
        
        // 重置滚动状态
        this.scrollIntoView = ''
        this.scrollTop = 0
        
        this.$nextTick(() => {
          setTimeout(() => {
            // 使用一个很大的数值强制滚动
            this.scrollTop = 999999
            console.log('强制滚动完成')
          }, 50)
        })
      } catch (error) {
        console.error('强制滚动失败:', error)
      }
    },
    
    // 获取当前用户
    getCurrentUser() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (currentUser) {
          return JSON.parse(currentUser)
        }
      } catch (error) {
        console.error('获取当前用户失败:', error)
      }
      return null
    },
    
    // 弹窗控制方法
    showEmojiPicker() {
      this.showEmojiModal = true
    },
    
    closeEmojiModal() {
      this.showEmojiModal = false
    },
    
    showMoreOptions() {
      this.showMoreOptionsModal = true
    },
    
    closeMoreOptions() {
      this.showMoreOptionsModal = false
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 工具方法
    getMessageClass(message) {
      const currentUser = this.getCurrentUser()
      if (!currentUser) return 'system-message'
      
      if (message.sender?.id === currentUser.id) {
        return 'my-message'
      } else if (message.sender?.id) {
        return 'other-message'
      } else {
        return 'system-message'
      }
    },
    
    getAvatarText(message) {
      if (message.sender?.name) {
        return message.sender.name.charAt(0).toUpperCase()
      }
      return 'S'
    },
    
    getMessageStatusIcon(status) {
      const statusMap = {
        'sending': '⏳',
        'sent': '✓',      // 单对钩表示已发送
        'delivered': '✓', // 单对钩表示已送达但未读
        'read': '✓✓'      // 双对钩表示对方已读
      }
      return statusMap[status] || ''
    },
    
    // 判断是否为自己的消息
    isMyMessage(message) {
      const currentUser = this.getCurrentUser()
      return currentUser && message.sender && message.sender.id == currentUser.id
    },
    
    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    
    // 清理资源（修复版）
    cleanup() {
      console.log('清理聊天页面资源...')
      
      // 取消消息管理器订阅
      if (this.roomId) {
        try {
          // 使用匿名函数作为占位符，因为实际的回调已经丢失
          chatMessageManager.unsubscribe(this.roomId, () => {})
        } catch (e) {
          console.warn('取消消息订阅失败:', e)
        }
      }
      
      // 取消状态管理器订阅
      try {
        // 使用匿名函数作为占位符，因为实际的回调已经丢失
        appStateManager.unsubscribe('server', () => {})
        appStateManager.unsubscribe('chat', () => {})
      } catch (e) {
        console.warn('取消状态订阅失败:', e)
      }
      
      // 清理旧的监听器（如果存在）
      try {
        // 使用正确的方法名
        chatService.removeMessageCallback(() => {})
        chatService.removeStatusCallback(() => {})
      } catch (e) {
        console.warn('清理监听器失败:', e)
      }
      
      console.log('聊天页面资源清理完成')
    },
    
    // 性能监控
    checkPerformance() {
      const startTime = performance.now()
      
      // 检查消息数量
      if (this.messages.length > 100) {
        console.warn('消息数量过多，可能影响性能:', this.messages.length)
      }
      
      // 检查滚动锁状态
      if (this.scrollLock) {
        console.warn('滚动锁未释放，可能存在性能问题')
      }
      
      const endTime = performance.now()
      console.log('性能检查完成，耗时:', endTime - startTime, 'ms')
    },
    
    // 清理旧消息（性能优化）
    cleanupOldMessages() {
      if (this.messages.length > 200) {
        // 保留最近100条消息
        this.messages = this.messages.slice(-100)
        this.saveMessages()
        console.log('已清理旧消息，当前消息数量:', this.messages.length)
      }
    },
    
    // 标记与当前聊天用户相关的通知为已读
    markUserNotificationsAsRead() {
      if (!this.currentChatUser || !this.currentChatUser.id) return;
      
      try {
        // 1. 更新通知中心的通知
        const allNotifications = JSON.parse(uni.getStorageSync('notifications') || '[]');
        let hasChanges = false;
        
        // 找出与当前用户相关的通知并标记为已读
        const updatedNotifications = allNotifications.map(notification => {
          // 检查是否是来自当前聊天用户的通知
          if (notification.type === 'chat' && 
              notification.data && 
              notification.data.userId == this.currentChatUser.id && 
              !notification.isRead) {
            hasChanges = true;
            return { ...notification, isRead: true };
          }
          return notification;
        });
        
        // 如果有更改，保存更新后的通知
        if (hasChanges) {
          uni.setStorageSync('notifications', JSON.stringify(updatedNotifications));
          console.log('已将与用户相关的通知标记为已读:', this.currentChatUser.id);
          
          // 更新通知角标
          try {
            notificationService.updateUnreadBadge();
          } catch (err) {
            console.error('更新通知角标失败:', err);
          }
          
          // 发送已读回执
          this.sendReadReceipt();
        }
        
        // 2. 更新聊天列表中的未读计数
        this.clearChatListUnreadCount();
        
      } catch (error) {
        console.error('标记通知为已读失败:', error);
      }
    },
    
    // 清除聊天列表中当前聊天的未读计数
    clearChatListUnreadCount() {
      try {
        // 获取聊天列表
        const chatListStr = uni.getStorageSync('chat_list');
        if (!chatListStr) return;
        
        const chatList = JSON.parse(chatListStr);
        if (!Array.isArray(chatList)) return;
        
        // 查找对应的聊天
        const chat = chatList.find(c => {
          // 检查直接匹配房间ID
          if (c.id === this.roomId) return true;
          
          // 检查私聊房间ID匹配
          if (c.id.startsWith('pm_')) {
            const m = /^pm_(\d+)_(\d+)$/.exec(c.id);
            if (m) {
              const id1 = parseInt(m[1]), id2 = parseInt(m[2]);
              return id1 == this.currentChatUser.id || id2 == this.currentChatUser.id;
            }
          }
          return false;
        });
        
        if (chat && chat.unreadCount > 0) {
          // 清除未读计数
          chat.unreadCount = 0;
          
          // 保存更新后的聊天列表
          uni.setStorageSync('chat_list', JSON.stringify(chatList));
          console.log(`已清除聊天 ${chat.id} 的未读消息计数`);
        }
      } catch (error) {
        console.error('清除聊天列表未读计数失败:', error);
      }
    },
    
    // 发送已读回执
    async sendReadReceipt() {
      if (!this.roomId || !this.messages || !this.messages.length || !chatService.isConnected) return;
      
      try {
        // 获取当前用户
        const currentUser = this.getCurrentUser();
        if (!currentUser) return;
        
        // 找出需要发送已读回执的消息（对方发送的且未标记为已读的）
        const unreadMessages = this.messages.filter(msg => 
          msg.sender && 
          msg.sender.id != currentUser.id && 
          msg.id && 
          msg.status !== 'read'
        );
        
        if (unreadMessages.length === 0) return;
        
        // 提取消息ID
        const messageIds = unreadMessages.map(msg => msg.id);
        
        // 构建已读回执消息
        const readReceiptMessage = {
          type: 'read_receipt',
          data: {
            room_id: this.roomId,
            message_ids: messageIds,
            reader_id: currentUser.id,
            timestamp: new Date().toISOString()
          }
        };
        
        // 发送已读回执
        if (chatService.ws && chatService.ws.readyState === WebSocket.OPEN) {
          chatService.ws.send(JSON.stringify(readReceiptMessage));
          console.log('已发送已读回执:', messageIds);
        } else {
          console.warn('WebSocket未连接，无法发送已读回执');
        }
        
      } catch (error) {
        console.error('发送已读回执失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  overflow: hidden; /* 防止整体页面滚动 */
}

/* 聊天头部 */
.chat-header {
  background: white;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.back-btn {
  background: #f8f9fa;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
  font-size: 24rpx;
  color: #333;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.user-status {
  font-size: 20rpx;
  color: #4CAF50;
}

.header-right {
  display: flex;
  gap: 12rpx;
  align-items: center;
}

.conn-status {
  font-size: 22rpx;
  color: #999;
}

.conn-status.connected { color: #4CAF50; }
.conn-status.disconnected { color: #F44336; }
.conn-status.error { color: #FF9800; }
.conn-status.connecting { color: #2196F3; }
.conn-status.reconnecting { color: #FFC107; }

.call-btn, .more-btn {
  background: #f8f9fa;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
  font-size: 24rpx;
  color: #333;
}

/* 消息列表 */
.message-list {
  flex: 1;
  padding: 20rpx;
  background: #f5f5f5;
  height: 0; /* 关键：让flex子元素正确计算高度 */
  overflow-y: auto; /* 确保可以滚动 */
}

.message-item {
  display: flex;
  margin-bottom: 20rpx;
  gap: 16rpx;
}

.message-item.my-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  overflow: hidden;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.my-message .message-avatar {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.other-message .message-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.system-message .message-avatar {
  background: #f0f0f0;
}

.avatar-text {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.system-message .avatar-text {
  color: #666;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.my-message .message-content {
  text-align: right;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.my-message .message-header {
  justify-content: flex-end;
}

.sender-name {
  font-size: 20rpx;
  color: #666;
  font-weight: bold;
}

.message-time {
  font-size: 18rpx;
  color: #999;
}

.message-body {
  margin-bottom: 4rpx;
}

.message-text {
  font-size: 24rpx;
  color: #333;
  line-height: 1.4;
  background: white;
  padding: 16rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  display: inline-block;
  word-wrap: break-word;
}

.my-message .message-text {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.system-message .message-text {
  background: #fff3cd;
  color: #856404;
  text-align: center;
  margin: 0 auto;
  max-width: 80%;
}

.message-image {
  max-width: 200rpx;
  max-height: 200rpx;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.message-file {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  padding: 12rpx 16rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.file-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.file-name {
  font-size: 22rpx;
  color: #333;
}

.message-status {
  text-align: right;
  margin-top: 4rpx;
  display: inline-block;
}

.status-icon {
  font-size: 14rpx;
  color: #4CAF50;
  margin-left: 6rpx;
  vertical-align: middle;
  opacity: 0.8;
}

/* 确保状态图标在消息气泡内 */
.my-message .message-status {
  text-align: right;
}

.other-message .message-status {
  display: none; /* 其他人的消息不显示状态 */
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
}

.loading-text {
  font-size: 22rpx;
}

/* 输入区域 */
.input-area {
  background: white;
  border-top: 1rpx solid #e0e0e0;
  padding: 16rpx;
  flex-shrink: 0; /* 防止输入区域被压缩 */
  position: relative; /* 确保固定在底部 */
}

.input-toolbar {
  display: flex;
  gap: 8rpx;
  margin-bottom: 12rpx;
}

.tool-btn {
  background: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 8rpx;
  padding: 8rpx 12rpx;
  font-size: 24rpx;
  color: #666;
}

.input-row {
  display: flex;
  gap: 12rpx;
  align-items: center;
}

.message-input {
  flex: 1;
  padding: 16rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 24rpx;
  background: #fafafa;
  max-height: 120rpx;
}

.message-input:focus {
  border-color: #4facfe;
  background: white;
}

.send-btn {
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: bold;
  min-width: 120rpx;
}

.send-btn:disabled {
  background: #ccc;
  color: #999;
}

/* 表情网格 - 使用全局SheetModal后的样式优化 */
.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8rpx;
  max-height: 400rpx;
  overflow-y: auto;
}

.emoji-item {
  font-size: 32rpx;
  text-align: center;
  padding: 16rpx;
  border-radius: 8rpx;
  transition: background-color 0.3s ease;
}

.emoji-item:active {
  background: #f0f0f0;
}

/* 选项列表 - 使用全局SheetModal后的样式优化 */
.options-list {
  padding: 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 24rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.option-item:last-child {
  border-bottom: none;
}

.option-item:active {
  background: #f5f5f5;
}

.option-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.option-text {
  font-size: 28rpx;
  color: #333;
}
</style>
